import cv2 as cv
import copy
import numpy as np
path = r'C:\Users\Administrator\Desktop\python\AI\material\rice.png'
img = cv.imread(path)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#a是阈值，bw是二值图
a,bw = cv.threshold(gray,0,0xff,cv.THRESH_OTSU)
#进行形态学滤波，减少噪点
#getStructuringElement生成卷积核
element = cv.getStructuringElement(cv.MORPH_CROSS,(3,3))
bw = cv.morphologyEx(bw,cv.MORPH_OPEN,element)
seg = copy.deepcopy(bw)

bin, cnts, hier = cv.findContours(seg, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
count = 0
rectangle = []#用于存放米粒矩形参数(w,h)
areas = []#用于存放米粒面积
for i in range(len(cnts), 0 ,-1):
	c = cnts[i-1]
	area = cv.contourArea(c)
	if area < 10:
		continue
	count+=1
	print('blob', i, "：", area)
	areas.append(area)
	x,y,w,h = cv.boundingRect(c)
	rectangle.append((w,h))
	cv.rectangle(img, (x,y),(x+w, y+h), (0,0,0xff),1)
	cv.putText(img,str(count), (x,y), cv.FONT_HERSHEY_PLAIN, 0.5, (0, 0xff, 0))


cv.imshow('origin',img)
cv.imshow('output',bw)
cv.waitKey()
cv.destroyAllWindows()

length = list(map(lambda x:np.linalg.norm(x),rectangle))#将矩形的对角线当作米粒长度

areas_mean = np.mean(areas)
len_mean  = np.mean(length)

areas_std = np.std(areas)
len_std = np.std(length)

print('米粒面积均值为:{}'.format(round(areas_mean,2)))
print('米粒面积方差为:{}'.format(round(pow(areas_std,2),2)))

print('米粒长度均值为:{}'.format(round(len_mean,2)))
print('米粒长度方差为:{}'.format(round(pow(areas_std,2),2)))
#计算面积在3sigma范围内米粒的数量
lower = areas_mean-3 * areas_std
upper = areas_mean+3 * areas_std
count = 0
for i in areas:
    if lower<i<upper:
        count+=1

print('米粒面积可信个数为:%d个' %count)

#计算长度在3sigma范围内米粒的数量
lower = len_mean-3 * len_std
upper = len_mean+3 * len_std
count = 0
for i in length:
    if lower<i<upper:
        count+=1

print('米粒长度可信个数为:%d个' %count)

